package fr.upmc.i3s.upmcontact.views.fragments;

import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
import fr.upmc.i3s.upmcontact.Constants;
import fr.upmc.i3s.upmcontact.R;
import fr.upmc.i3s.upmcontact.backend.BackEndBridgeImpl;
import fr.upmc.i3s.upmcontact.callbacks.IGetDataCallback;
import fr.upmc.i3s.upmcontact.content.collectors.CollectorsController;
import fr.upmc.i3s.upmcontact.content.collectors.UpdateDatesManager;
import fr.upmc.i3s.upmcontact.content.containers.CollectedContentManager;
import fr.upmc.i3s.upmcontact.content.containers.IContainer;
import fr.upmc.i3s.upmcontact.contents.MerchantInfo;
import fr.upmc.i3s.upmcontact.librairies.pulltorefresh.PullToRefreshBase;
import fr.upmc.i3s.upmcontact.librairies.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import fr.upmc.i3s.upmcontact.librairies.pulltorefresh.PullToRefreshScrollView;
import fr.upmc.i3s.upmcontact.listeners.OnPublishedClickListener;
import fr.upmc.i3s.upmcontact.tools.BitmapFactoryAdapter;
import fr.upmc.i3s.upmcontact.tools.DateUtils;
import fr.upmc.i3s.upmcontact.tools.FileUtils;
import fr.upmc.i3s.upmcontact.views.FragmentController;
import fr.upmc.i3s.upmcontact.views.fragments.models.IFragmentModel;
import fr.upmc.i3s.upmcontact.views.fragments.models.PageFragmentModel;

public class FeedMerchantsInfosFragment extends PageFragmentModel implements IFragmentModel {
	
	private static final String TAG = "FeedMerchantsInfosFragment";
	
	private FragmentController fragmentController;
	private static volatile FeedMerchantsInfosFragment INSTANCE;
	
	private PullToRefreshScrollView prsvContent;
	private TableLayout tlFeed;
	private TextView tvFeetLeft;
	private TextView tvFeetRight;
	private ImageView ivArrowLeft;
	private ImageView ivArrowRight;
	
	public static FeedMerchantsInfosFragment getInstance() {
		if(INSTANCE == null) {
			FeedMerchantsInfosFragment fragment = new FeedMerchantsInfosFragment();
		    Bundle bundle = new Bundle(3);
		    bundle.putInt(EXTRA_LAYOUT_FRAGMENT, R.layout.fragment_feed);
		    bundle.putInt(EXTRA_HEAD_ICON, R.drawable.ic_menu_merchant_white);
		    bundle.putInt(EXTRA_HEAD_TEXT, R.string.title_fragment_infos_merchants);
		    fragment.setArguments(bundle);
		    INSTANCE = fragment;
		}
	    return INSTANCE;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	
 	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.initFragmentViews();
		this.fragmentController = (FragmentController) getActivity();
		fetchViews();
		customizeViews();
		setListeners();
	}
 	
 	@Override
 	public void fetchViews() {
 		this.prsvContent = (PullToRefreshScrollView) this.getView().findViewById(R.id.pullToRefreshScrollview_content);
 		this.tlFeed = (TableLayout) this.getView().findViewById(R.id.tableLayout_feed);
 		this.tvFeetLeft = (TextView) this.getView().findViewById(R.id.textView_feet_text_left);
 		this.tvFeetRight = (TextView) this.getView().findViewById(R.id.textView_feet_text_right);
 		this.ivArrowLeft = (ImageView) this.getView().findViewById(R.id.imageView_feet_arrow_left);
 		this.ivArrowRight = (ImageView) this.getView().findViewById(R.id.imageView_feet_arrow_right);
 	}
 	
 	@Override
 	public void customizeViews() {
 		this.tvFeetLeft.setText("");
 		this.tvFeetRight.setText("");
 		this.ivArrowLeft.setVisibility(View.GONE);
 		this.ivArrowRight.setVisibility(View.GONE);
 		// set last update date for pull to refresh :
 		updateDate();
 		// fill table row feed with informations :
 		fillFeed();
 	}
 	
 	@Override
 	public void setListeners() {
 		this.prsvContent.setOnRefreshListener(onContentRefreshListener);
 	}
 	
	private void updateDate() {
 		this.prsvContent.getLoadingLayoutProxy().setLastUpdatedLabel(
 				fragmentController.getString(R.string.pull_to_refresh_last_update)+" "+
 				DateUtils.toDisplayDateTime(UpdateDatesManager.retrieveUpdateMerchantsInfosDate(fragmentController)));
	}
 	
 	private void fillFeed() {
 		tlFeed.removeAllViews();
 		LayoutInflater inflater = (LayoutInflater) fragmentController.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 		boolean photoOnLeft = false;
 		for(MerchantInfo mi : CollectedContentManager.getInstance(getActivity()).getMerchantsInfos()) {
 			Log.i(TAG, "MerchantInfo="+mi);
 			tlFeed.addView(createRowForInformation(inflater, mi, photoOnLeft));
 			tlFeed.addView(createSeparator(inflater));
 			photoOnLeft = !photoOnLeft;
 		}
 	}
 	
 	private View createRowForInformation(LayoutInflater inflater, MerchantInfo mi, boolean photoOnLeft) {
 		View row;
 		if(photoOnLeft) {
 			row = inflater.inflate(R.layout.layout_row_merchant_info_left, null);
 		} else {
 			row = inflater.inflate(R.layout.layout_row_merchant_info_right, null);
 		}
 		// fetch views
 		ImageView ivPhoto = (ImageView) row.findViewById(R.id.imageView_row_merchant_info);
 		TextView tvTitle = (TextView) row.findViewById(R.id.textView_row_merchant_info_title);
 		TextView tvStatus = (TextView) row.findViewById(R.id.textView_row_merchant_info_promo_status);
 		TextView tvAddress = (TextView) row.findViewById(R.id.textView_row_merchant_info_address);
 		TextView tvDescription = (TextView) row.findViewById(R.id.textView_row_merchant_info_description);
 		TextView tvLink = (TextView) row.findViewById(R.id.textView_row_merchant_info_link);
 		TextView tvDate = (TextView) row.findViewById(R.id.textView_row_merchant_info_published_at_date);
 		TextView tvHour = (TextView) row.findViewById(R.id.textView_row_merchant_info_published_at_hour);
 		TextView tvPublishedBy = (TextView) row.findViewById(R.id.textView_row_merchant_info_published_by);
 		// custom views
 		tvTitle.setText(mi.getTitle());
 		tvAddress.setText(mi.getMerchantAddress());
 		tvDescription.setText(mi.getDescription());
 		tvLink.setText(mi.getLink());
 		tvDate.setText(DateUtils.toDisplayDate(mi.getCreatedAt()));
 		tvHour.setText(DateUtils.toDisplayTime(mi.getCreatedAt()));
 		tvPublishedBy.setText(getActivity().getString(R.string.display_by_publisher)+" "+mi.getPublishedBy().getUsername());
 		if(mi.getPhotoPath() != null) { 
 			Bitmap bm = BitmapFactoryAdapter.decodeFile(mi.getPhotoPath(), 250);
 			ivPhoto.setImageBitmap(bm);
 		}
 		switch(mi.getPromotionStatus()) {
 		case MerchantInfo.STATE_SHORTLY_AVAILABLE:
 			tvStatus.setTextColor(Color.BLUE);
 			tvStatus.setText(R.string.display_shorly_available);
 			break;
 		case MerchantInfo.STATE_ONGOING:
 			tvStatus.setTextColor(Color.GREEN);
 			tvStatus.setText(R.string.display_ongoing);
 			break;
 		case MerchantInfo.STATE_ENDED:
 			tvStatus.setTextColor(Color.RED);
 			tvStatus.setText(R.string.display_ended);
 			break;
 		}
 		// set listeners
 		row.setOnClickListener(new OnPublishedClickListener(this, mi));
 		// change IDs
 		int randId = (int) Math.round(Math.random()*1000);
 		row.setId(row.getId()+randId);
 		tvTitle.setId(tvTitle.getId()+randId);
 		tvStatus.setId(tvStatus.getAutoLinkMask()+randId);
 		tvAddress.setId(tvAddress.getId()+randId);
 		tvDescription.setId(tvDescription.getId()+randId);
 		tvLink.setId(tvLink.getId()+randId);
 		tvDate.setId(tvDate.getId()+randId);
 		tvHour.setId(tvHour.getId()+randId);
 		tvPublishedBy.setId(tvPublishedBy.getId()+randId);
 		ivPhoto.setId(ivPhoto.getId()+randId);
 		return row;
 	}
 	
    private View createSeparator(LayoutInflater inflater) {
        View separator = inflater.inflate(R.layout.layout_separator, null);
        return separator;
    }
 	
 	
 	  ///////////////
 	 // CALLBACKS //
 	///////////////
 	
	private IGetDataCallback getMerchantsInfosCallback = new IGetDataCallback() {
		@Override
		public void getDataEndedOk(LinkedList<Object> list) {
			Log.i(TAG, "FeedMerchantsInfosFragment.getDataEndedOk.list.size="+list.size());
			CollectedContentManager.getInstance(fragmentController).getMerchantsInfos().updateWith(list);
			UpdateDatesManager.storeMerchantsInfosUpdateDate(getActivity());
			// sort by ascending date
			CollectedContentManager.getInstance(fragmentController).getMerchantsInfos().sortBy(IContainer.DESCENDING);
			// save content for offline access :
			CollectedContentManager.getInstance(fragmentController).getMerchantsInfos().saveState(fragmentController);
			// delete unused local files :
			List<String> exceptedFiles = CollectedContentManager.getInstance(fragmentController).getMerchantsInfos().getRequiredExternalFileList();
			FileUtils.rmAllFilesInDirectoryExcept(Constants.MERCHANTS_EXTERNAL_FOLDER, exceptedFiles);
	 		// re-use dialog in backendbridge
			BackEndBridgeImpl.getInstance(fragmentController).setCancelForAWhile(false);
			// set last update date for pull to refresh :
	 		updateDate();
			// feel feed view :
			fillFeed();
			prsvContent.onRefreshComplete();
		}
		@Override
		public void getDataEndedNok() {
			Log.w(TAG, "getMerchantsInfosCallback.getDataEndedNok");
			prsvContent.onRefreshComplete();
		}
	};
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private OnRefreshListener<ScrollView> onContentRefreshListener = new OnRefreshListener<ScrollView>() {
		@Override
		public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
			Log.i(TAG, "onContentRefreshListener.onRefresh");
			CollectorsController.getInstance(fragmentController)
			.getMerchantsInfosCollector()
			.collect(fragmentController, getMerchantsInfosCallback, true, true);
		}
	};
	
}
